<template>
  <section class="test-content " v-loading="loading" :element-loading-text="loadingText"
    element-loading-background="rgba(0, 0, 0, 0.8)">
    <div class="classroom-main">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item class="hander" to="/index">首页</el-breadcrumb-item>
        <el-breadcrumb-item>测试</el-breadcrumb-item>
      </el-breadcrumb>
      <h3 class="title" v-html="title1"></h3>
      <div class="test-main">
        <div class="test-left">
          <h3 class="name" v-html="title"></h3>
          <div class="test-all">
            <el-radio-group v-model="radio" class="marn-radio" v-show="type=='1' || type=='4'">
              <div class="dxt-main" v-for="(item,index) in list">
                <el-radio :label="index">{{item.label}}.{{item.old}}</el-radio>
              </div>
            </el-radio-group>
            <div class="tkt-main" v-for="(item,index) in list" v-show="type=='3' || type=='5'">
              <span class="name">({{index+1}})、</span>
              <!-- <el-input v-model="item.new"></el-input> -->
              <el-input v-model="item.new" class="main-txt" v-show="type=='3'"></el-input>
              <el-input v-model="item.new" type="textarea" class="main-txt" v-show="type=='5'"></el-input>
            </div>
            <el-checkbox-group v-model="checkList" class="marn-radio" v-show="type=='2'">
              <div class="dxt-main" v-for="(item,index) in list">
                <el-checkbox :label="item.label + '.' + item.old"></el-checkbox>
              </div>

            </el-checkbox-group>
            <div style="clear:both"></div>
          </div>
          <div class="next" @click="next" v-show="(index+1)<zong &&isnext && !issubmit">下一题</div>
          <div class="next" @click="next" v-show="(index+1)==zong &&isnext && !issubmit">交卷</div>
          <div class="next" v-show="(index+1)<zong &&isnext && issubmit">提交中...</div>
        </div>
        <div class="test-right">
          <div class="time" v-show="curStartTime">剩余时间：<span style="color:#0962a8">{{min}}:{{second}}</span></div>
          <div class="card">
            <!-- <h3 class="card-title">答题卡</h3> -->
            <h3 class="card-title" v-if="danxuanList.length!=0">单选题</h3>
            <div class="card-content">
              <div class="card-item" v-if="item.examType=='1'" v-for="(item,index) in cardList" :class="item.addClass">
                  {{index+1}}
              </div>
            </div>

            <h3 class="card-title" v-if="duoxuanList.length!=0">多选题</h3>
            <div class="card-content">
              <div class="card-item" v-if="item.examType=='2'" v-for="(item,index) in cardList" :class="item.addClass">
                  {{index+1}}
              </div>
            </div>

            <h3 class="card-title" v-if="tiankongList.length!=0">填空题</h3>
            <div class="card-content">
              <div class="card-item" v-if="item.examType=='3'" v-for="(item,index) in cardList" :class="item.addClass">
                  {{index+1}}
              </div>
            </div>

            <h3 class="card-title" v-if="panduanList.length!=0">判断题</h3>
            <div class="card-content">
              <div class="card-item" v-if="item.examType=='4'" v-for="(item,index) in cardList" :class="item.addClass">
                  {{index+1}}
              </div>
            </div>

            <h3 class="card-title" v-if="jiandaList.length!=0">简答题</h3>
            <div class="card-content">
              <div class="card-item" v-if="item.examType=='5'" v-for="(item,index) in cardList" :class="item.addClass">
                  {{index+1}}
              </div>
            </div>
            <div class="submit" @click="submit">交卷</div>
            <div style="clear:both"></div>
          </div>
        </div>
        <div style="clear:both"></div>
      </div>
    </div>
  </section>
</template>

<script>
  import Cookies from 'js-cookie'
  import { Notification } from 'element-ui';
  import { MessageBox } from 'element-ui';
  export default {
    crollToTop: true,
    props: {

    },
    head() {
      return {
        title: '测试',
      }
    },
    data() {
      return {
        loading: false,
        course: true,
        isnext: true,
        issubmit: false,
        zong: '',
        loadingText: '数据加载中',
        testList: [

        ],
        cardList: [

        ],
        content: {
          arr: []
        },
        title1: '',
        title: '',
        timeDate: 0,
        list: [],
        checkList: [],
        type: '2',
        allTest: [],
        indexMain: 0,
        index: 0,
        goods: true,
        radio: null,
        input: '',
        day: '',
        hour: '',
        min: '',
        timer: null,
        allTime: null,
        testEnd: false,
        second: '',
        curStartTime: null,
        id: '',
        courseId: '',
        paperId: '',
        date:'',
        now:'',
        endDate:'',
        end:'',
        leftTime:'',
        h:'',
        m:'',
        s:'',
        danxuanList:[],
        duoxuanList:[],
        tiankongList:[],
        panduanList:[],
        jiandaList:[],
      }
    },

    computed: {

    },
    created() {
      this.courseId = this.$route.params.id1;
      this.paperId = this.$route.params.id2;
      this.detailsId = this.$route.params.id3;

      //this.clearTest();
    },
    mounted() {
      this.getId();
      $('.el-scrollbar__wrap').animate({
        scrollTop: '0px'
      }, 0);
      window.addEventListener('beforeunload', e => this.beforeunloadFn(e))
    },
    destroyed() {
      window.removeEventListener('beforeunload', e => this.beforeunloadFn(e))
    },
    beforeDestroy() {
      clearInterval(this.timer);
      this.timer = null;
    },
    methods: {
      beforeunloadFn(e) {
          console.log('刷新或关闭')
          window.localStorage.setItem("yemian", "1");
          window.opener.location.reload();
        },
      submit() {
        var that = this;
        var len = that.cardList.length;
        if ((that.index + 1) != len) {
          Notification.warning({
            title: '提示',
            message: "您的试题还没做完"
          })
          return;
        }
        this.next();

      },
      next() {
        var obj = {};
        obj.examAnswer = this.allTest[this.index].examAnswer;
        obj.examType = this.allTest[this.index].examType;
        obj.id = this.allTest[this.index].id;
        obj.score = this.allTest[this.index].score;
        if (this.allTest[this.index].examType == "3" || this.allTest[this.index].examType == "5") {
          var arr = [];
          this.allTest[this.index].data.forEach((item, i) => {
            arr.push(item.new)
          })
          obj.newExamAnswer = arr.join(",");
        }

        if (this.allTest[this.index].examType == "1" || this.allTest[this.index].examType == "4") {
          var list = this.allTest[this.index].data;
          if (this.radio != null) {
            obj.newExamAnswer = list[this.radio].label;
          }

        }
        if (this.allTest[this.index].examType == "2") {
          var list = this.allTest[this.index].examLabel;
          var arr = [];
          this.allTest[this.index].data.forEach((item, i) => {
            this.checkList.forEach((item1, i1) => {
              let a = item.label + '.' + item.old;
              if (a == item1) {
                arr.push(item.label)
              }
            })
          })
          obj.newExamAnswer = arr.join(",");
        }

        if (obj.newExamAnswer == "," || !obj.newExamAnswer) {
          Notification.warning({
            title: '提示',
            message: "请做题"
          });
          return;
        }
        if ((this.index + 1) == this.zong) {
          this.loading = true;
          this.loadingText = "数据提交中,请稍后..."
          console.log(33366)
          setTimeout(() => {
            this.submitData(obj, true);
          }, 800)
        } else {
          this.submitData(obj, false);
        }


      },
      getId() {
        let that = this;
        that.loading = true;
        this.$axios.$post("/f/startUserPaper?paperId=" + this.paperId)
          .then(function(response) {
            that.title1 = response.data.educationPaper.title;
            that.id = response.data.id;
            var now = new Date();
            //如果试卷有测试时长则判断倒计时
            if(response.data.educationPaper.testTimeSecond){
              var time = now.getTime() + response.data.educationPaper.testTimeSecond * 1000;
              that.allTime = response.data.educationPaper.testTimeSecond;
              var a = that.formatDate(time);
              that.curStartTime = a;
              that.countTime();
              that.showTime();
            }

            that.getList();
          })
          .catch(function(error) {
            // handle error
            console.log(error);
          })
      },

      submitData(obj, b) {
        if (!Cookies.get("token")) {
          this.$router.push("/login");
          return;
        };
        this.issubmit = true;
        let that = this;
        this.$axios.$post("/f/saveExamRecord?examId=" + obj.id + "&remainTime=" + this.timeDate + "&submitPaper=" + b +
            "&userAnswer=" + obj.newExamAnswer + "&userPaperId=" + this.id + "&paperId=" + this.paperId +
            "&rootCourseId=" + this.courseId + "&courseType=1&detailsId=" + this.detailsId)
          .then(function(response) {
            if ((that.index + 1) < that.zong) {
              that.index = that.index + 1;
              if (that.index == that.zong) {
                that.isnext = false;
              }
              that.cardList.forEach((item, i) => {
                if (i == that.index) {
                  item.addClass = "active-item"
                }

              })
              that.type = that.allTest[that.index].examType;
              that.list = that.allTest[that.index].data;
              that.title = that.allTest[that.index].examQuestion;
              that.radio = null;
              that.checkList = [];
            } else {
              that.beforeunloadFn()
              that.$router.push("/result1/" + that.id + "/" + that.courseId);
            }


            that.issubmit = false;

          })
          .catch(function(error) {
            // handle error
            console.log(error);
            that.issubmit = false;
          })
      },
      nextA() {
        console.log(this.radio);
        if (this.radio == null) {
          Notification.warning({
            title: '提示',
            message: "请选择答案"
          })
          return;
        }
        var obj = {
          "educationExamSubjectList": [{
            "examAnswer": this.content.examAnswer,
            "newExamAnswer": this.cardList[this.indexMain].arr[this.radio].select,
            "examType": this.content.examType,
            "score": this.content.score
          }],
          "paperId": this.$route.params.id
        };
        var that = this;
        this.$axios.$post("http://seed.ckwashington.com/admin/mini/exam/savePaperRecord", obj)
          .then(function(response) {
            console.log(response, 88998777)
            var len = that.cardList.length;
            if (that.indexMain + 1 == len) {
              that.$router.push("/mainAll/result/" + that.$route.params.id)
            } else {
              that.indexMain = that.indexMain + 1;
              that.content = that.cardList[that.indexMain];
              that.testList = that.content.arr;

              that.radio = null;
              if (that.indexMain + 1 == len) {
                that.isNext = false;
              }
              for (var i = 0; i < len; i++) {
                if (i == that.indexMain) {
                  that.cardList[i].addClass = "active-item"
                } else {
                  that.cardList[i].addClass = ""
                }
              }
            }

          })
          .catch(function(error) {
            // handle error
            console.log(error);
          })
      },
      formatDate(date) {
        date = new Date(date);
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        var d = date.getDate();
        var h = date.getHours();
        var m1 = date.getMinutes();
        var s = date.getSeconds();
        m = m < 10 ? ("0" + m) : m;
        m1 = m1 < 10 ? ("0" + m1) : m1;
        d = d < 10 ? ("0" + d) : d;
        return y + "-" + m + "-" + d + " " + h + ":" + m1 + ":" + s;
      },

      countTime() {
        // 获取当前时间
        this.date = new Date()
        this.now = this.date.getTime()
        // 设置截止时间
        this.endDate = new Date(this.curStartTime) // this.curStartTime需要倒计时的日期
        this.end = this.endDate.getTime()
        // 时间差
        this.leftTime =this.end - this.now
        // 定义变量 d,h,m,s保存倒计时的时间
        if (this.leftTime >= 0) {
          // 天
          this.day = Math.floor(this.leftTime / 1000 / 60 / 60 / 24)
          // 时
          this.h = Math.floor(this.leftTime / 1000 / 60 / 60 % 24)
          this.hour = this.h < 10 ? '0' + this.h : this.h
          // 分
          this.m = Math.floor(this.leftTime / 1000 / 60 % 60)
          this.min = this.m < 10 ? '0' + this.m : this.m
          // 秒
          this.s = Math.floor(this.leftTime / 1000 % 60)
          this.second = this.s < 10 ? '0' + this.s : this.s
        } else {
          this.day = 0
          this.hour = '00'
          this.min = '00'
          this.second = '00'

        }

      },
      //设置每秒调用此函数
      showTime() {

        this.timer = setInterval(() => {
          if(this.curStartTime){
            this.countTime();
            if (Number(this.hour) === 0 && Number(this.day) === 0 && Number(this.min) === 0 && Number(this.second) === 0) {

              clearInterval(this.timer)
              this.timer = null;
              this.$confirm('本堂测试已结束,请点击确认按钮查看测试结果', '提示', {
                confirmButtonText: '确定',
                showCancelButton: false,
                showClose: false,
                closeOnClickModal:false,
                type: 'warning'
              }).then(() => {
                clearInterval(this.timer)
                this.$router.push("/result1/" + this.id + "/" + this.courseId);
                return;
              }).catch(() => {

              });
            }
          }
        }, 1000)
      },
      goContent(item) {
        //this.$router.push("/mainAll/teacherContent")
      },
      getList() {
        let that = this;

        this.$axios.$get("/f/examByPaperId?id=" + this.id + "&paperId=" + this.paperId)
          .then(function(response) {
            console.log(response, 333)
            // that.title1 = response.data[0].content;
            that.zong = response.data.length;
            let data = response.data;
            let arr = [];
            let arr1 = [];
            if (data.length != 0) {
              data.forEach((item, i) => {
                if(item.examType == '1'){
                  that.danxuanList.push(item)
                }
                if(item.examType == '2'){
                  that.duoxuanList.push(item)
                }
                if(item.examType == '3'){
                  that.tiankongList.push(item)
                }
                if(item.examType == '4'){
                  that.panduanList.push(item)
                }
                if(item.examType == '5'){
                  that.jiandaList.push(item)
                }

                var listObj = {}
                listObj.examType = item.examType;
                if (i == 0) {
                  listObj.addClass = "active-item"
                } else {
                  // listObj.addClass = ""
                }
                arr1.push(listObj);
                item.examQuestion = item.content;
                item.examAnswer = item.educationExamOptionList;

                // item.examLabel = item.educationExamSubject.examLabel;
                item.examStem = item.educationExamOptionList;
                let obj = {};
                obj.examQuestion = item.content;
                obj.examAnswer = item.examAnswer;
                // console.log(obj.examAnswer,121366);
                // debugger;
                obj.examType = item.examType;
                // obj.examLabel = item.educationExamSubject.examLabel;
                obj.id = item.id;
                obj.score = item.score;
                if (item.examType == "3" || item.examType == "5") {
                  let arr1 = [];
                  console.log(3)
                  let data1 = item.educationExamAnswerList;
                  if (data1.length != 0) {
                    data1.forEach((item1, i1) => {
                      let obj1 = {};
                      obj1.old = item1.answer;
                      obj1.new = "";
                      arr1.push(obj1)
                    })
                  }
                  obj.data = arr1;
                }
                if (item.examType == "1" || item.examType == "2" || item.examType == "4") {
                  let arr1 = [];
                  let data1 = item.examStem;
                  if (data1.length != 0) {
                    data1.forEach((item1, i1) => {
                      if (item1 != "") {
                        let obj1 = {};
                        obj1.old = item1.content;
                        obj1.new = "";
                        obj1.label = item1.label;
                        arr1.push(obj1)
                      }

                    })
                  }
                  obj.data = arr1;
                }
                arr.push(obj)
              })
              that.cardList = arr1;
              that.type = arr[0].examType;
              that.list = arr[0].data;
              that.title = arr[0].examQuestion;
              that.allTest = arr;

            //答题卡显示题目类型


              console.log(that.cardList, 123456)
            }

            that.loading = false;
          })
          .catch(function(error) {
            // handle error
            console.log(error);
          })
      },
      getData() {
        var that = this;
        this.loading = true;
        this.$axios.$post('http://seed.ckwashington.com/admin/mini/exam/queryExamPaperDetail?paperId=' + this.$route
            .params.id)
          .then(function(response) {
            that.title = response.data.title;
            var data = response.data.educationExamSubjectList;
            var len = data.length;
            for (var i = 0; i < len; i++) {
              if (i == 0) {
                data[i].addClass = "active-item"
              } else {
                data[i].addClass = ""
              }
              that.content = data[0];
              that.testList = data[0].arr;
              data[i].list = data[i].examStem.split("~~~");
              data[i].list1 = data[i].examLabel.split(",");
              var len1 = data[i].list1.length;
              data[i].arr = [];
              for (var k = 0; k < len1; k++) {
                var obj = {};
                obj.name = data[i].list[k];
                obj.select = data[i].list1[k];
                data[i].arr.push(obj);
              }
            }
            that.cardList = data;
            that.loading = false;
          })
          .catch(function(error) {
            // handle error
            console.log(error);
          })
      }
    }
  }
</script>

<style lang="less">
  .test-content {
    width: 100%;
    float: left;

    .tkt-main {
      width: 100%;
      margin-bottom: 8px;
      float: left;

      .name {
        margin: 20px 0 !important;
      }
    }

    .marn-radio {
      width: 100%;
      float: left;
    }

    .dxt-main {
      width: 100%;
      height: 55px;
      background: #f8f8f8;
      margin-bottom: 8px;
      float: left;
      display: flex;
      align-items: center;
      padding-left: 12px;
      box-sizing: border-box;

      .el-radio {
        display: flex;
        align-items: center;

      }

      .el-checkbox {
        display: flex;
        align-items: center;
      }
    }

    .main-txt {
      width: calc(100% - 100px);
      margin-top: 4px;
    }

    .tkt-main .name {
      width: 50px !important;
      line-height: 10px;
      font-size: 12px;
    }

    .teacher-img {
      width: 100%;
      display: block;
    }

    .classroom-main {
      width: 1200px;
      margin: 0 auto;

      .el-breadcrumb {
        margin: 30px 0;
        font-size: 15px;
        padding-left: 10px;
      }

      .title {
        width: 100%;
        line-height: 70px;
        font-size: 20px;
        color: #222222;
        text-align: center;
        box-shadow: 0 0px 7px #c7cac7;
        margin-bottom: 15px;
      }

      .test-main {
        width: 100%;
        margin-bottom: 80px;

        .test-right {
          width: 280px;
          float: right;

          .card {
            width: 100%;
            box-shadow: 0 0px 7px #c7cac7;
            margin-top: 15px;
            padding-top: 15px;
            .submit {
              width: calc(100% - 40px);
              height: 45px;
              text-align: center;
              line-height: 45px;
              font-size: 18px;
              color: #fff;
              background: #0962a8;
              margin:10px 20px;
              cursor: pointer;
              float: left;
            }
            .card-content {
              width: 100%;
              // margin-top: 30px;
              margin: 10px 0;
              padding: 0 20px;
              float: left;
              .card-item {
                width: 25px;
                height: 25px;
                line-height: 25px;
                text-align: center;
                margin-right: 5px;
                float: left;
                font-size: 14px;
                color: #222222;
                border: 1px solid #222222;
                box-sizing: border-box;
                margin-bottom: 5px;
              }

              .active-item {
                background: #0962a8;
                border: 0;
                color: #fff;
              }
            }

            .card-title {
              width: 100%;
              line-height: 20px;
              padding-left: 20px;
              // border-left: 3px solid #0962a8;
              box-sizing: border-box;
              font-size: 18px;
              text-align: left;
            }
          }

          .time {
            height: 40px;
            line-height: 40px;
            text-align: center;
            font-size: 16px;
            color: #222222;
            width: 100%;
            box-shadow: 0 0px 7px #c7cac7;
          }
        }

        .test-left {
          width: 900px;
          float: left;
          padding: 30px;
          box-shadow: 0 0px 7px #c7cac7;

          .name {
            width: 100%;
            line-height: 30px;
            margin: 25px 0;
            padding-left: 10px;
            text-align: left;
            font-size: 16px;
            color: #777777;
            font-weight: 500;
            background: #ffffff;
          }

          .next {
            width: 140px;
            height: 40px;
            line-height: 40px;
            text-align: center;
            color: #fff;
            font-size: 18px;
            background: #17a2b8;
            margin: 80px auto;
            cursor: pointer;
          }

          .test-all {
            width: 100%;
            background: #fff;

            .el-radio-group {
              width: 100%;
              padding: 0 20px;

              .el-radio {
                color: #606266;
                cursor: pointer;
                margin-right: 30px;
                width: 100%;
                height: 55px;
                text-align: left;

                .el-radio__label {
                  line-height: 55px;
                }
              }
            }
          }
        }
      }
    }

    .loadmore {
      font-size: 16px;
      padding: 14px 30px;
      margin-bottom: 120px;
      margin-top: 70px;
    }

    .teacher-main {
      display: flex;
      justify-content: space-between;
      flex-wrap: wrap;
      width: 1200px;
      margin: 0 auto;

      .teacher-item {
        box-shadow: 0 1px 8px 0 rgba(0, 0, 0, 0.1);
        cursor: pointer;
        background: #ffffff;
        border-radius: 5px;
        width: 280px;
        height: 130px;
        margin-bottom: 30px;

        img {
          width: 100%;
          height: 100%;
          display: block;
        }
      }
    }
  }
</style>
